import Tpl from './index.ejs';
import AddTpl from './add.ejs';
import ListTpl from './list.ejs';

class Permission {

    init ($wrap, router) {
		let self = this;

		this.render($wrap, router, function () {

			$('.ui.checkbox').checkbox();
	        $('.dropdown').dropdown();

			self.$listWrap = $('#listWrap');
			self.reqData = {};
			self.listData = [];

			self.bindEvent();
		});
	}

	bindEvent () {
		let self = this;

		$('#permissionAddBtn').on('click', function () {
			self.submitForm();
		});
	}

	submitForm () {
        let self = this;
        self.reqData = $.extend({
			paged: true,
        	pageNo: 1,
        	pageSize: 10
        }, Tools.getFromData());

        $.ajax({
			url: '/admin/permission/add',
			method: 'post',
			data: JSON.stringify(reqData),
			dataType: 'json',
			success: function (data) {

				if (data && data.message === 'SUCCESS') {

					alert('添加成功');
				}
                else {
                    alert('添加失败');
                }
			}
        });
	}

    render ($wrap, router, callback) {
		if (!router) {
            $wrap.html(Tpl());
        }
        else {
            switch (router) {
               	case 'add':

                    $wrap.html(AddTpl());
                    callback();
               		break;
                case 'list':

                    $.ajax({
            			url: '/admin/permission/list',
            			method: 'post',
            			data: JSON.stringify({}),
            			dataType: 'json',
            			success: function (data) {

            				if (data && data.message === 'SUCCESS') {

                                $wrap.html(ListTpl(data));
                                callback();
            				}
            			}
                    });

               		break;
               	default:
               		break;
            }
        }
	}
}

export default new Permission();
